import { message } from "@/utils/message";
import { computed } from "vue";
import { updateAdvertisementStatus } from "@/api/advertisement";

// 基础地址配置
const BASE_URL = "https://exhibition-bucket.oss-cn-beijing.aliyuncs.com";

// 需是hooks写法（函数中有return），避免失去响应性
export function useColumns(
  advertisementList: any,
  handleViewCallback?: (row: any) => void,
  handleEditCallback?: (row: any) => void,
  handleRefreshCallback?: () => void
) {
  // 使用computed来保持响应性
  const tableData = computed(() => {
    return advertisementList.value || [];
  });

  const columns: TableColumnList = [
    {
      label: "广告图片",
      prop: "ad_img",
      cellRenderer: ({ row }) => {
        // 拼接广告图片地址
        const adImgUrl = row.ad_img
          ? `${BASE_URL}${row.ad_img}`
          : "/placeholder-ad.png";
        return (
          <img
            src={adImgUrl}
            alt="广告图片"
            style="width: 50px; height: 50px; object-fit: cover;"
          />
        );
      }
    },
    {
      label: "审批状态",
      prop: "status",
      width: 120,
      align: "center",
      cellRenderer: ({ row }) => {
        let statusText = "";
        let statusType = "";

        switch (row.status) {
          case 0:
            statusText = "审核中";
            statusType = "warning";
            break;
          case 1:
            statusText = "已通过";
            statusType = "success";
            break;
          case 2:
            statusText = "已退回";
            statusType = "danger";
            break;
          case 3:
            statusText = "待提交";
            statusType = "warning";
            break;
          default:
            statusText = "未知";
            statusType = "info";
        }

        return <el-tag type={statusType}>{statusText}</el-tag>;
      }
    },
    {
      label: "操作",
      fixed: "right",
      width: 220,
      cellRenderer: ({ index, row }) => (
        <>
          <el-button size="small" onClick={() => handleView(index + 1, row)}>
            查看
          </el-button>
          <el-button size="small" onClick={() => handleEdit(index + 1, row)}>
            修改
          </el-button>
          <el-button
            size="small"
            type="danger"
            onClick={() => handleSubmit(index + 1, row)}
          >
            提交审批
          </el-button>
        </>
      )
    }
  ];

  const handleView = (index: number, row) => {
    // 查看模式：任何状态都可以查看
    if (handleViewCallback) {
      handleViewCallback(row);
    } else {
      message(`您查看了第 ${index} 行，数据为：${JSON.stringify(row)}`, {
        type: "success"
      });
    }
  };

  const handleEdit = (index: number, row) => {
    // 统一拦截提示：0 审核中、1 已通过
    if (row.status === 0) {
      message("广告正在审核中，不能修改", { type: "warning" });
      return;
    }
    if (row.status === 1) {
      message("广告已通过，不能修改", { type: "warning" });
      return;
    }

    if (handleEditCallback) {
      handleEditCallback(row);
    } else {
      message(`您修改了第 ${index} 行，数据为：${JSON.stringify(row)}`, {
        type: "success"
      });
    }
  };

  const handleSubmit = async (index: number, row) => {
    // 状态：0=审核中，1=已通过，2=未通过，3=待提交
    if (row.status === 0) {
      message("已提交，不可重复审批", { type: "warning" });
      return;
    }
    if (row.status === 1) {
      message("已通过，不可重复审批", { type: "warning" });
      return;
    }
    if (row.status !== 2 && row.status !== 3) {
      message("只有未通过或待提交状态才能提交审批", { type: "warning" });
      return;
    }

    try {
      // 调用API更改状态
      const result: any = await updateAdvertisementStatus({
        id: row.id,
        exhibitor_id: row.exhibitor_id,
        status: 0 // 将状态改为0（审核中）
      });

      if (result.code === 1) {
        message("提交审批成功！", { type: "success" });
        // 刷新列表
        if (handleRefreshCallback) {
          handleRefreshCallback();
        }
      } else {
        message(result.msg || "提交审批失败！", { type: "error" });
      }
    } catch (error) {
      console.error("提交审批失败:", error);
      message("提交审批失败，请重试", { type: "error" });
    }
  };

  return {
    columns,
    tableData
  };
}
